﻿using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using System;
using System.Collections.Generic;
using System.Linq;

namespace VisionSurface.Web.Filters
{
    /// <summary>
    /// 枚举模型验证器
    /// </summary>
    public class EnumModelValidator : IModelValidator
    {
        public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context)
        {
            var value = context.Model;
            if (value != null)
            {
                var valueType = value.GetType();

                if (!Enum.IsDefined(valueType, value))
                {
                    return new List<ModelValidationResult>
                {
                    new ModelValidationResult("", $"Invalid value for enum {valueType.Name}")
                };
                }
            }

            return Enumerable.Empty<ModelValidationResult>();
        }
    }
}
